package cn.liontalk.rabbitmq;

import cn.liontalk.common.redis.RedisService;
import cn.liontalk.common.redis.prefix.MiaoShaKey;
import cn.liontalk.common.result.CodeMsg;
import cn.liontalk.config.RabbitmqConfig;
import cn.liontalk.controller.LoginController;
import cn.liontalk.dao.SecKillDao;
import cn.liontalk.entity.MiaoshaMessage;
import cn.liontalk.entity.OrderInfo;
import cn.liontalk.entity.User;
import cn.liontalk.service.GoodsService;
import cn.liontalk.service.SecKillService;
import cn.liontalk.vo.GoodsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: 周哲
 * @package: cn.liontalk.rabbitmq
 * @description:
 * @date: 2019/1/23 21:18
 * @version: V1.0
 */
@Service
public class MQreceiver {

    private static Logger log = LoggerFactory.getLogger(LoginController.class);


    @Autowired
    GoodsService goodsService;

    @Autowired
    SecKillService secKillService;


    @Autowired
    private RedisService redisService;

    private static final String APPED ="Receive : ";


    @RabbitListener(queues="queue")
    public void receive(String message){
        System.out.println(APPED +message);
    }


    @RabbitListener(queues = RabbitmqConfig.TOPIC_QUEUE1)
    public void receiveTopicQueueOne(String message){
        System.out.println(APPED +message);
    }



    @RabbitListener(queues = RabbitmqConfig.TOPIC_QUEUE2)
    public void receiveTopicQueueTwo(String message){
        System.out.println(APPED +message);
    }


    @RabbitListener(queues = RabbitmqConfig.MIAOSHA_QUEUE)
    public void receiveMiaoShaMessage(String message){
        log.info("==============================================================receive Message Is :" + message);
        MiaoshaMessage miaoshaMessage = RedisService.stringToBean(message,MiaoshaMessage.class);
        long goodsId = miaoshaMessage.getGoodId();
        User user = miaoshaMessage.getUser();


        GoodsVO goodsVO = goodsService.queryGoodsById(goodsId);
        int stockCount = goodsVO.getStock();
        if (stockCount <= 0) {
            return;
        }
        OrderInfo orderInfo = secKillService.queryGoodsKillInfoByGoodsIdAndUserId(goodsId, user.getId());
        if (null != orderInfo) {
            return ;
        }
        secKillService.mqSecKillGoods(user, goodsVO);
        redisService.set(MiaoShaKey.hasKillThisGoods,""+user.getId()+"_" + goodsId,String.class);
    }

}
